import os,sys
import requests
import random
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import *
import functools
import time
from datetime import datetime
import platform
from pynput import keyboard
import xml.etree.ElementTree as ET
import xmltodict

wx_package = "com.tencent.mm"
wx_mainActivity = "com.tencent.mm.ui.LauncherUI"
agents = [
		"Mozilla/5.0 (Linux; Android 10; V2002A Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/111.0.5563.116 Mobile Safari/537.36",
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x6309071d) XWEB/8447 Flue",
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ????/1.0.0 Chrome/102.0.5005.167 Electron/19.1.8 Safari/{}.36".format(random.randint(1, 580)),
		"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ifonts_client/2.4.4 Chrome/87.0.4280.141 Electron/11.5.0 Safari{}.36".format(random.randint(1, 580)),
		"maxthon/6.2.0.1000 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/{}.36".format(random.randint(1, 580)),
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/{}.0".format(random.randint(1, 113))
	]

myHeaders = {
	"Connection":"keep-alive",
	"User-Agent":"Mozilla/5.0 (Linux; Android 10; V2002A Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/111.0.5563.116 Mobile Safari/537.36 XWEB/5317 MMWEBSDK/20230805 MMWEBID/3781 MicroMessenger/8.0.42.2460(0x28002A54) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64",
	"Accept":"image/wxpic,image/tpg,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
	"X-Requested-With":"com.tencent.mm",
	"Sec-Fetch-Site":"cross-site",
	"Sec-Fetch-Mode":"no-cors",
	"Sec-Fetch-Dest":"image",
	"Referer":"https://www.114yygh.com/",
	"Accept-Encoding":"gzip, deflate",
	"Accept-Language":"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}
'''
	https://www.114yygh.com/wechat/appointmentRegister
	https://www.114yygh.com/mobile/department/hos/list?_time=1698716210686&hosCode=H01110003
	https://www.114yygh.com/mobile/common/content?_time=1698716210190&label=hosProclamation&bizType=HOSPITAL&hosCode=H01110003
	https://www.114yygh.com/mobile/hospital/detail?_time=1698716210190&hosCode=H01110003
	https://www.114yygh.com/mobile/hospital/authority?_time=1698716210190&hosCode=H01110003
	https://www.114yygh.com/mobile/collections/user/hospital/check?_time=1698716210486&hosCode=H01110003
	https://www.114yygh.com/wechat/hospital?hosCode=H01110003
'''
IsMac = platform.system() != "Windows"

user = os.getlogin()
userHome = "C:/Users/{}".format(user)
logPath = "{}/Desktop/logs".format(userHome)


def getMyName(callback = False,Line = False):
    frameInfo = sys._getframe(1)
    lineNum = frameInfo.f_lineno
    if callback:
        return frameInfo.f_back.f_code.co_name
    return [frameInfo.f_code.co_name,frameInfo.f_back.f_code.co_name,lineNum]


def TryRun(func):
    defName = getMyName()
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            # log.info("开始执行 {}".format(func.__name__))
            return res
        except Exception as e: 
            except_type, except_value, except_traceback = sys.exc_info()
            log.error("{} 执行失败 {} ".format(func.__name__,e.__dict__.get("msg")))
            # log.error("{0} {1}方法执行失败， 原因 {2}".format(defName ,func.__name__,e))
            return None
        
    return wrapper

def GetDateTime(formatStr = "%Y-%m-%d %H:%M:%S",timestamp = False):
	if timestamp:
		return "%d" % (time.time() * 1000)
	now = time.strftime(formatStr,time.localtime())
	# time.ctime()
	return now

def CheckFolder(pathname):
    if not os.path.exists(pathname):
        os.makedirs(pathname)

def NowDate(format_str = "%Y-%m-%d %H:%M:%S"):
    return time.strftime(format_str,time.localtime())

class Log():
    def __init__(self,logName = "",Echo = True):
        self.logName = logName
        self.Echo = Echo
        CheckFolder(logPath)
    @TryRun
    def WriteMsg(self,msg):
        now_date = NowDate(format_str = "%Y%m%d%H")
        with open("{}/{}{}.log".format(logPath,self.logName,now_date),"a",encoding = "utf-8") as f:
            f.write(msg)
            f.close()

    def info(self,*args):
        frameInfo = sys._getframe(1)
        lineNum = frameInfo.f_lineno
        funcname = frameInfo.f_back.f_code.co_name
        now_date = NowDate()
        msg = now_date+" INFO {0} {1}行 ".format(funcname,lineNum )
        for m in args :
            msg += " {}".format(m)
            
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)

    def error(self,*args):
        funcname ,line = getMyName(callback = True)
        now_date = NowDate()
        msg = now_date+" error {0} {1}行 ".format(funcname,line )
        for m in args :
            msg += " "
            msg += m
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)

    def warning(self,*args):
        funcname ,line = getMyName(callback = True)
        now_date = NowDate()
        msg = now_date+" warning {0} {1}行 ".format(funcname,line )
        for m in args :
            msg += " "
            msg += m
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)

log = Log(logName = "pku_run")

def GetDriver(show = True,isRandom = True,mobile = False):
	chrome_options = webdriver.ChromeOptions()
	chrome_options.add_argument("--no-sandbox")
	chrome_options.add_experimental_option('excludeSwitches', ['disenable-automation'])
	mobile_emulation = {"deviceName": "iPhone X"}
	if mobile:
		chrome_options.add_argument("--window-size=340,900")
		chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

	if isRandom:
		chrome_options.add_argument('--user-agent={}'.format(random.choice(agents)))
	if not show:
		chrome_options.add_argument('headless')  # 不显示界面

	chrome_options.binary_location = "H:/Program Files/Google/Chrome/Application/chrome.exe"
	chrome_driver = "H:/WebDriver/chromedriver.exe"
	server = Service(executable_path=chrome_driver)
	browser = webdriver.Chrome(service=server, options=chrome_options)
	# browser.set_window_size(200,900) 
	return browser



@TryRun
def HighLight(driver = None,element = None,time_num = 0.1):
    #封装好的高亮显示页面元素的方法
    #使用JavaScript代码将传入的页面元素对象的边框颜色
    #3次循环，边框颜色先蓝后红中间各停留1秒，产生闪烁效果
    if element == None:
        return
    try:
        for i in range(0,3):

            driver.execute_script("arguments[0].setAttribute('style',arguments[1]);",
                              element, "border:2px solid green;")
            sleep(time_num)
            driver.execute_script("arguments[0].setAttribute('style',arguments[1]);",
                              element, "border:2px solid blue;")
            sleep(time_num)
        #恢复页面元素原装
        driver.execute_script("arguments[0].setAttribute('style',arguments[1]);",
                              element, "")
    except Exception as e:
        pass


class TryClick():
    def __init__(self,Ele = None ,Xpath = None,Css = None ,Class = None,Name = "",driver = None,source = "",sleepNum = 0.2):
        self.ele = Ele
        self.xpath = Xpath
        self.class_name =  Class
        self.css = Css
        self.name = Name
        self.source = source
        self.driver = driver
        # if Name != "":
        #     log.info("TryClick 点击{}".format(Name))

        if self.xpath != None:
            # print("xpath点击")
            self.XpathClick()
        elif self.css != None:
            # print("css点击")
            self.Css_Click()
    
    def Click(self,num = 1,actClick = False,scriptClick = False):
        defName = getMyName()
        if actClick == True and scriptClick == True:
            log.info("点击过")
            return
        if self.ele != None:
            if self.driver != None:
                time.sleep(1)
                HighLight(driver = self.driver, element = self.ele)
                
            try:
                for i in range(num):
                    try:
                        self.ele.click()
                        log.info("{} 点击{} ".format(self.source,self.name))
                    except Exception as e:
                        pass
                    
                    
                # log.info("已点击")
                return True
            except ElementClickInterceptedException as e:
                if self.driver != None:
                    if not scriptClick:
                        log.info("通过script点击")
                        self.driver.execute_script("arguments[0].click();", self.ele)
                        scriptClick = True
                    if not actClick:
                        log.error("点击失败，元素禁用{},尝试坐标点击".format(self.name))
                        x,y = self.ele.rect.get("x"),self.ele.rect.get("y")
                        ActionChains(self.driver).move_by_offset(x, y).click().perform()
                        actClick = True
                return self.Click(num = num,actClick = actClick,scriptClick = scriptClick)
            except Exception as e:
                log.error(e)
                return False
        else:
            log.error("ele {} 未获取到".format(self.name))
            return False

    def XpathClick(self):
        pass
    def Css_Click(self):
        pass

@TryRun
def clear(ele):
    if IsMac:
        ele.send_keys(Keys.COMMAND,"a")
        ele.send_keys(Keys.DELETE)
    else:
        ele.send_keys(Keys.CONTROL,"a")
        ele.send_keys(Keys.DELETE)


def GetEleMsg(Ele = None,word = ""):
	if Ele != None:
		
		try:
			if word != "" :
				return Ele.get_attribute("placeholder")
			return Ele.text
		except Exception as e:
			return ""
		 
	return ""


class TrySend():
    def __init__(self,Ele = None ,Xpath = None,Css = None ,Class = None,Msg = "",driver = None,source = ""):
        self.ele = Ele
        self.xpath = Xpath
        self.class_name =  Class
        self.css = Css
        self.msg = Msg
        self.source = source
        self.driver = driver
        self.Run()

    @TryRun
    def Run(self):
        if self.ele != None:
            clear(self.ele)
            time.sleep(1)
            self.ele.send_keys(self.msg)
        else:
            log.error("组件不存在")

@TryRun
def Element(driver, item = None,name = "",name1 = "" ,toType = "css",islist = False,tryNum = 0,source = ""):
    CllInfo = getMyName()
    title = name
    ele = None
    if islist:
        ele = []
    if driver == None and item == None:
        return ele
    tryNum +=1
    if tryNum > 3:
        return ele
    
    thewindow = ""
    
    findType = By.CSS_SELECTOR

    findName = ".{}".format(title)

    
    if toType == "class":
        findType = By.CLASS_NAME
        findName = "{}".format(name) 

    if toType == "id":
        findType = By.ID
        findName = "{}".format(name) 

    if toType == "xpath":
        findType = By.XPATH
        findName = "{}".format(name) 

    if toType == "name":
        findType = By.NAME
        findName = "//*[contains(text(), '{}')]".format(name) 

    if toType == "tag":
        findType = By.TAG_NAME
        findName = title

    if toType == "xpath":
        findType = By.XPATH
        findName = title

    if toType == "link":
        log.info("通过 linkText查找")
        findType = By.LINK_TEXT
        findName = title

    if toType == "partial":
        log.info("通过 partial linkText查找")
        findType = By.PARTIAL_LINK_TEXT
        findName = title
    


    if tryNum == 2 and name1 != "":
        # log.warning("来源 {} 改为通过name1 获取元素组件".format(CllInfo))
        title = name1
                
    if driver != None :
        # if tryNum > 2:
        #     isTrue = hasattr(driver, 'window_handles')
        #     if isTrue:
        #         # thewindow = driver.current_window_handle
        #         Handllers = driver.window_handles
        #         for j in range(len(Handllers)):
        #             driver.switch_to.window(Handllers[j])
        #             try:
        #                 if islist:
        #                     ele = []
        #                     if item != None:
        #                         ele = item.find_elements(findType,findName)
        #                     else:
        #                         ele = driver.find_elements(findType,findName)
        #                     if  ele:
        #                         # log.info("{}在第{}个window 当前窗口 {}".format(findName,j+1,Handllers[j]))
        #                         break
        #                 else:
        #                     if item != None:
        #                         ele = item.find_element(findType,findName)
        #                     else:
        #                         ele = driver.find_element(findType,findName)
        #                     if ele != None :
        #                         # log.info("{}在第{}个window 当前窗口 {}".format(findName,j+1,Handllers[j]))
        #                         break
        #             except Exception as e:
        #                 pass
        try:
            if islist:
                ele = []
                if item != None:
                    ele = item.find_elements(findType,findName)
                else:
                    ele = driver.find_elements(findType,findName)
            else:
                if item != None:
                    ele = item.find_element(findType,findName)
                else:
                    ele = driver.find_element(findType,findName)
        except Exception as e:
            pass 
    else:
        log.error("driver 未获取到") 
    
    if ele != None or ele:
        # log.warning("{} 已获取到".format(findName))
        return ele
    else:
        return Element(driver = driver,name = name,name1 = name1,toType = toType,islist = islist,tryNum = tryNum,source = source)


class HospitalApi():
	def __init__(self):
		super(HospitalApi, self).__init__()
		self.cookies = None
		self.Register()
	def Register(self):
		t = GetDateTime()
		handers = {
			"Connection":"keep-alive",
			"User-Agent":"Mozilla/5.0 (Linux; Android 10; V2002A Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/111.0.5563.116 Mobile Safari/537.36 XWEB/5317 MMWEBSDK/20230805 MMWEBID/3781 MicroMessenger/8.0.42.2460(0x28002A54) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64",
			"Accept":"image/wxpic,image/tpg,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
			# "X-Requested-With":"com.tencent.mm",
			"Sec-Fetch-Site":"cross-site",
			"Sec-Fetch-Mode":"no-cors",
			"Sec-Fetch-Dest":"image",
			"Referer":"https://www.114yygh.com/",
			"Accept-Encoding":"gzip, deflate",
			"Accept-Language":"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
		}
		to_url = "https://www.114yygh.com"
		session = requests.session()
		# session.cookies["SECKEY_ABVK"] = "fEBqUcmZaaf2ZW0ChWEwyvUGVdsEp1WlglsnjUUD7Ds%3D"
		# session.cookies["BMAP_SECKEY"]="6FS8vLk20G-JTxlBxlus1HWWfrpQPcRg8_Iqz8VfcQ-YdZAxHwV4N-PEwwJHU9CE1d1X_IBjB-tjrpsah6pMYjPC7mnzyFnm9C0WVqlyMMqeYeOTX-SJvVyXWBjIzsqqXcT5XvUXk5Gv1rjZ8oIM_rEWHEXWG917USubeLgP-gzaD9YLEDdaAY-RVO-nfo0Z"
		# session.cookies["_opt"]="mobile_wxauth_e3c90815d7192942c48316620d5c7b96"
		# session.cookies["cmi-user-ticket"]="yb05X7BurCjp4wJ5oDsoAMGKN2-20lIjwjNWnQ.."
		# session.cookies["imed_session"]="bPWlEGyio43LXsFJdFzQtreitEN3R4or_5662394"
		# session.cookies["imed_session_tm"] = t

		res = session.get(url = to_url,headers = handers,verify = False)
		cookie = res.cookies
		self.cookies = requests.utils.dict_from_cookiejar(cookie)

		# with open("my.html","w") as f:
		# 	f.write(res.text)
		# 	f.close()
	def Run(self):
		t = GetDateTime()
		to_url = "https://www.114yygh.com/mobile/department/hos/list?_time={}&hosCode=H01110003".format(t)
		#https://www.114yygh.com/mobile/accredit/callback&response_type=code&scope=snsapi_base&state=mobile_wx_accredit_req_url6556018e-f90c-4878-ac01-aabc4ebf0ddb&connect_redirect=1#wechat_redirect"
		res = requests.get(url = to_url,headers = myHeaders,verify = False,cookies = self.cookies)
		print(res.text)

def browser():
	browser = GetDriver(show = False)
	browser.get("https://www.114yygh.com")
	touch = Element(By.CSS_SELECTOR,"goto.v-link.clickable")
	skip_btn = Element(driver = browser,name = "v-button.white")
	
	
	if touch != None:
		time.sleep(2)
		TryClick(Ele = touch).Click()
	print(browser.page_source)
	time.sleep(2)
	if skip_btn != None:
		print(GetEleMsg(Ele = skip_btn))
		TryClick(Ele = skip_btn).Click()
		# print("后退")
		# browser.back()

	
	show_tip = Element(driver = browser,name = "driver-popover-title")
	print(skip_btn)
	print(show_tip)
	print(touch)
	TryClick(driver = browser,Ele = show_tip,Name = "弹框").Click()
	
	TryClick(driver = browser,Ele = skip_btn,Name = "跳过").Click()
	input_box = Element(driver = browser,name = "el-input__inner")
	print(GetEleMsg(Ele = input_box,word = "placeholder"))
	TryClick(driver = browser,Ele = input_box,Name = "输入框").Click()
	TrySend(driver = browser,Ele = input_box,Msg = "中国医学科学院北京协和医院")
	search_btn = Element(driver = browser,name = "search-btn.v-link.highlight.clickable.selected")
	TryClick(driver = browser,Ele = search_btn,Name = "搜索按钮").Click()
	xiehe = Element( driver = browser,toType = "link",name = "中国医学科学院北京协和医院")


	# hospital-title
	print(xiehe)
	time.sleep(10)

def appiumTest():
    from appium import webdriver
    import time
     
    desired_caps = {
        "automationName":"UiAutomator2",
        "platformVersion":"12",
        "dontStopAppOnReset":True, 
        "platformName": "Android",   
        "deviceName": "127.0.0.1:62025",      
        "appPackage": wx_package,      
        "appActivity": wx_mainActivity,  
        "skipServerInstallation": False,
        "noReset":True
    }
     
    # 创建WebDriver对象并初始化Appium服务器
    driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_capabilities=desired_caps)
    
    def on_press(key):
        log.info('按下了键盘上的 {0}'.format(key))
        if key == keyboard.Key.down:
            print(driver.page_source)
            eles = Element(driver = driver,name = "android.widget.FrameLayout",toType = "class",islist = True)
            print(len(eles))
            tree = ET.parse(driver.page_source)
            for i in eles:
                print(i)

            ele_list = Element(driver = driver,toType = "xpath",islist = True,name = '//android.widget.FrameLayout[@resource-id="com.tencent.mm:id/w_"]/android.widget.FrameLayout[1]/android.widget.FrameLayout/android.widget.FrameLayout[4]/android.widget.RelativeLayout/android.widget.FrameLayout[3]')
            print(len(ele_list))
            for j in ele_list:
                print(j.text)
    def on_release(key):
        log.info('松开了键盘上的 {0}'.format(key))
        if key == keyboard.Key.down:
            # 如果按下ESC键则关闭程序
            print(driver.page_source)

    with keyboard.Listener(on_press = on_press,on_release = on_release) as listener:
        listener.join()
    return
    # 等待5秒钟，确保应用已经完全加载
    # driver.implicitly_wait(5)
    
    # help(driver)
    
    log.info(driver.get_window_position())
    log.info(driver.get_window_rect())
    w,h = driver.get_window_size().get("width"),driver.get_window_size().get("height")
    # App()
    # 
    search_btn = Element(driver = driver,name = "com.tencent.mm:id/jha",toType = "id")
 
    TryClick(Ele = search_btn,driver = driver).Click()
    search_input = Element(driver = driver,name = "com.tencent.mm:id/d98",toType = "id")
    
    TrySend(driver = driver,Ele = search_input ,Msg = "北京大学口腔医院医疗服务助手")
    driver.implicitly_wait(2)
    
    search_res = Element(driver = driver,name = "com.tencent.mm:id/odf",toType = "id")
    if search_res.text == "北京大学口腔医院医疗服务助手":
        TryClick(Ele = search_res,driver = driver,Name = "北京大学口腔医院医疗服务助手").Click()
    driver.implicitly_wait(5)
    num = 0
    while True:
        if num > 10:
            log.info("10次未监测到弹框")
            break
        alert_ele = Element(driver = driver,name = "com.tencent.mm:id/mm_alert_cancel_btn",toType = "id")
        if alert_ele != None:
            log.info("监测到弹框，点击稍后再看")
            TryClick(Ele = alert_ele,driver = driver,Name = "稍后再看").Click(num = 2)
           
            driver.tap([(241, 721)])
            # ele = driver.find_element(By.LINK_TEXT,"稍后再看")
            # TryClick(Ele = ele,driver = driver,Name = "稍后再看").Click(num = 2)
            break
        time.sleep(1)
        num +=1
    time.sleep(2)
    log.info(driver.page_source)
    yy = Element(driver = driver,name = "预约挂号",toType = "link")
    TryClick(Ele = yy,driver = driver,Name = "稍后再看").Click(num = 2)
    # alert_ele = Element(driver = driver,name = "com.tencent.mm:id/mm_alert_cancel_btn",toType = "id")
    
    
    return
    while True:
        text = Element(driver = driver,name = "最近",toType = "name")
        start_element =  Element(driver = driver,name = "com.tencent.mm:id/cj1",toType = "id")
        print(start_element)
        if text != None:
            break
        else:
            driver.swipe(w / 2, 100, w / 2, h * 0.8,3000)
            # driver.scroll(text,start_element,3000)
    
    driver.implicitly_wait(5)
    print(driver.page_source)
def App():
    import uiautomator2 as u2 
    now = datetime.now()
    driver = u2.connect_wifi("172.19.52.142")
    # driver = u2.connect_wifi("172.19.209.166")
    # driver = u2.connect("000003362c42202e")
    # driver = u2.connect("127.0.0.1:62025")
    items = ["jln","jla","jlg"]
    # for i in items:
    #     ys = driver(resourceId="com.tencent.mm:id/{}".format(i))
    #     print(ys.exists(),ys.center())
      
    #     time.sleep(1)
    # driver.click(269.5, 1352.5)
    def test():
        print(driver.dump_hierarchy())

    
    def toClick(ele):
        num = 0
        while True:
            try:
                if ele.exists():
                    print("点击事件")
                    ele.click()
                    break
                elif num == 0:
                    print("等待元素出现")
                    print(driver.dump_hierarchy())
                    num +=1
                elif num >30:
                    break
            except Exception as e:
                pass

            
            time.sleep(1)


    # print(driver.dump_hierarchy())
    print(driver.device_info)
    # driver.app_start(package_name = wx_package)
    print(driver.app_info(package_name = wx_package))

    print("滑动进入小程序列表")
    time.sleep(1)
    while True:
        try:
            ele_exists =  driver(text = "最近").exists()
        except Exception as e:
            pass
        if ele_exists != None and ele_exists  :
            break
        else:
            driver.swipe_ext("down")
    time.sleep(2)
    print("点击小程序")
    toClick(driver(resourceId = "com.tencent.mm:id/obc",text = "北京大学口腔医院医疗服务助手"))
    return
    
    # time.sleep(10)
    print(driver.dump_hierarchy())
    
    
    # driver.click(0.327, 0.566)
    num = 0
    while True:
        btn = driver(resourceId="com.tencent.mm:id/jla",text = "稍后再看") 
        print(btn.exists())
        if btn.exists():
            print("点击稍后再看")
            btn.click()
            break
        num +=1
        time.sleep(1)
        if num > 12:
            break
    driver.click(269.5, 1352.5)
    driver.click(0.331, 0.568)
    titleItem = driver(resourceId = "com.tencent.mm:id/hc")
    if titleItem.exists():
        print("已进入小程序",titleItem.get_text())
    
    
    print("点击预约")
    driver(text = "预约挂号").click_exists(timeout = 30)
   
    time.sleep(1)
    print("点击输入")
    toClick(driver(text = "搜索科室、医生"))
    print("输入框")
    time.sleep(1)
    toClick(driver(text="综合"))
    time.sleep(1)
    
    toClick(driver(text="[魏公村总院区·科室] 综合治疗科牙周门诊"))
    # driver(text="[魏公村总院区·科室] 综合治疗科口腔综合门诊").click()
    toClick(driver(text="许成志"))
    time.sleep(2)
    print(driver(resourceId = "com.tencent.mm:id/hc").get_text())
    toClick(driver(text="12-16"))
    driver.xpath('//android.widget.CheckBox/android.widget.TextView[1]').click()
    time.sleep(2)
    toClick(driver(text="确定"))
    print(driver.dump_hierarchy())
if __name__ == '__main__':
	# hospital = HospitalApi()
	# hospital.Run()
	# App()
    # appiumTest() 
    tree = ET.parse("1.xml")
    root = tree.getroot()
     
    with open("1.xml","r",encoding = "utf-8") as f:
        xml_data = f.read()
        data_dict = xmltodict.parse(xml_data)
        t = data_dict["hierarchy"]["android.widget.FrameLayout"]["android.widget.FrameLayout"]["android.widget.FrameLayout"]
        print(t)
        print(len(t))
        print(t.keys())
    xml_data = """
    <bookstore>
      <book>
        <title>Python for Beginners</title>
        <author>John Smith</author>
        <price>29.95</price>
      </book>
      <book>
        <title>Python Advanced Topics</title>
        <author>Jane Doe</author>
        <price>39.95</price>
      </book>
    </bookstore>
    """
    data_dict = xmltodict.parse(xml_data)
    print(data_dict.keys())
    print(data_dict["bookstore"]["book"][0])
    def recursive_print(element, indent=""):
        # 打印当前元素的标签和属性
        print(f"{indent}标签: {element.tag}, 属性: {element.attrib}")

        # 打印当前元素的文本内容
        if element.text:
            print(f"{indent}文本: {element.text.strip()}")

        # 递归打印子元素
        for child in element:
            recursive_print(child, indent + "    ")

    # 从根元素开始打印内容
    # recursive_print(root)